

#include "StatusServer.h"
#include "../ConfigMgr.h"
#include "../log.h"

#include <thread>

#include <boost/asio.hpp>
#include <nlohmann/json.hpp>

void RunServer()
{
    auto config = ConfigMgr::GetConfig();
    std::string host = config->StatusServerInfo.IP + ":" + std::to_string(config->StatusServerInfo.Port);
    
    // 创建服务对象
    StatusServerImpl service;

    // 监听端口和添加服务
    grpc::ServerBuilder builder;
    builder.AddListeningPort(host, grpc::InsecureServerCredentials());
    builder.RegisterService(&service);
    
    // 构建并启动gRPC服务器
    std::unique_ptr<grpc::Server> server(builder.BuildAndStart());
    log_info("StatusServer listening on {}", host);

    // 创建Boost.Asio的io_context
    boost::asio::io_context ioc;
    // 创建signal_set用于捕获SIGINT信号
    boost::asio::signal_set signals(ioc, SIGINT, SIGTERM);
    signals.async_wait([&](boost::system::error_code error, int si){
        if(error)
        {
            log_error("StatusServer signal error: {}", error.message());
            return;
        }
        
        log_info("StatusServer is shutting down...");
        server->Shutdown();
        ioc.stop();
    });

    // 运行io_context
    std::thread([&ioc](){
        ioc.run();
    }).detach();

    // 等待服务器关闭
    server->Wait();
}

int main(void)
{
    try
    {
        RunServer();
    }
    catch (const std::exception& e)
    {
        log_error("StatusServer exception: {}", e.what());
        return -1;
    }

    return 0;
}